import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Cascader,
  Button,
  Table,
  Divider,
  Badge,
  Modal,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { TableListData } from './data';

const { Option } = Select;

const badgeStatus: any = ['error', 'success'];
const badgeText = ['禁用', '启用'];

const qrCodePath = '/thanos/posthouse/qrcode';

const { pathname } = window.location;
const { Item } = Form;
interface PostManagementListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: TableListData;
  gardenList: any;
  INITINFO: any;
  location: { query?: any };
  screen: string;
  hasPath: boolean;
}

interface PostManagementListState {
  searchValues: any;
  codeVisible: boolean;
  codeId: number;
  shwoCode: string;
  statusVisible: boolean;
  statusId: number;
  statusType: number;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    postManagementList: { dataInfo, gardenList },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    gardenList,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['postManagementList/fetch'],
  }),
)
class PostManagementListElem extends React.Component<PostManagementListProps,
PostManagementListState> {
  columns: any = [
    {
      title: '编号',
      dataIndex: 'code',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '驿站',
      dataIndex: 'name',
      width: 140,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditPosthouse(record.id, record.name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '小区',
      dataIndex: 'gardenName',
      width: 140,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '地址',
      dataIndex: 'address',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isValid',
      width: 80,
      render: (text: number) => <Badge status={badgeStatus[text]} text={badgeText[text]} />,
    },
    {
      title: '服务时间',
      dataIndex: 'serverTiem',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '套餐',
      dataIndex: 'tariffName',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      dataIndex: 'id',
      fixed: 'right',
      width: 140,
      render: (id: any, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEditPosthouse(id, record.name)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeStatusModal(true, record)}>
            {record.isValid ? '禁用' : '启用'}
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeCodeModal(true, id)}>
            二维码
          </span>
        </>
      ),
    },
  ];

  state: PostManagementListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    codeVisible: false,
    codeId: 0,
    shwoCode: '',
    statusVisible: false,
    statusId: 0,
    statusType: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.handleValidation();
    this.fetchAction('common/fetchAddressList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clearGarden');
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    const params = this.turnValuesType(searchValues);
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const {
      provinceCode,
      cityCode,
      countyCode,
      ...query
    } = values;
    const codes = [provinceCode, cityCode, countyCode];

    return {
      ...query,
      areaCodes: codes.filter((item: any) => item),
    };
  };

  fetchDataValues = () => {
    const { provinceCode, cityCode, countyCode } = this.getQueryParams();
    this.fetchAction('fetch', this.getQueryParams());
    if (this.getQueryParams().countyCode) {
      this.fetchAction('fetchGarden', { provinceCode, cityCode, countyCode });
    }
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  /**
   * 新建驿站
   */
  handleAddPosthouse = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建驿站',
      url: '/basic/postManagement/list/add',
    });
  };

  /**
   * 编辑驿站
   */
  handleEditPosthouse = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/postManagement/list/edit?id=${id}`,
    });
  };

  handleValidation = () => {
    const { form: { getFieldValue } } = this.props;
    const value = getFieldValue('areaCodes');
    if (value.length) {
      const params = {
        pareaCode: value[0],
        careaCode: value[1],
        dareaCode: value[2],
      };
      this.fetchAction('fetchGarden', params);
    }
  };

  handleChangeCodeModal = (codeVisible: boolean, id?: number) => {
    const { shwoCode } = this.state;
    this.setState({
      codeVisible,
      codeId: id || 0,
      shwoCode: id ? `${qrCodePath}?posthouseId=${id}` : shwoCode,
    });
  };

  handleChangeStatusModal = (statusVisible: boolean, row?: any) => {
    this.setState({
      statusVisible,
      statusId: row ? row.id : 0,
      statusType: row ? Number(Boolean(!row.isValid)) : 0,
    });
  };

  handleChangeStatusSure = () => {
    const { searchValues: search, statusId: id, statusType: isValid } = this.state;
    const params = { search, id, isValid };
    this.fetchAction('changeStatus', params);
    this.handleChangeStatusModal(false);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;
      const { areaCodes = [], ...params } = values;
      const query = {
        ...params,
        pageIndex: 1,
        pageSize: 10,
      };
      if (areaCodes.length) {
        [query.provinceCode] = [areaCodes[0]];
        [query.cityCode] = [areaCodes[1]];
        [query.countyCode] = [areaCodes[2]];
      }

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '驿站管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    this.fetchAction('clearGarden');
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `postManagementList/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      pageIndex,
      pageSize,
      codeVisible,
      codeId,
      shwoCode,
      statusVisible,
      statusType,
    } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      gardenList,
      INITINFO: { addressList },
      screen,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm paddingB12">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={24}>
              <Col md={6} sm={24}>
                <Item label="驿站名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　省市区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader changeOnSelect options={addressList} placeholder="请选择" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　小区" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      onFocus={this.handleValidation}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col md={6} sm={24}>
                <Item label="驿站编号" colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddPosthouse}
            >
              新建驿站
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          visible={codeVisible}
          title="二维码"
          footer={null}
          width={400}
          onCancel={() => this.handleChangeCodeModal(false)}
        >
          <div style={{ textAlign: 'center' }}>
            <img src={shwoCode} alt="" className="marginB20" />
            <a href={`${qrCodePath}?posthouseId=${codeId}&type=1`} style={{ display: 'block' }}>
              保存二维码
            </a>
          </div>
        </Modal>

        <Modal
          title="确认提示"
          visible={statusVisible}
          onOk={this.handleChangeStatusSure}
          onCancel={() => this.handleChangeStatusModal(false)}
        >
          <p>确定{statusType ? '启用' : '禁用'}该驿站?</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<PostManagementListProps>()(PostManagementListElem);
